package controllerLayer;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import modelLayer.Password;

public class PasswordController {	
	
	
	public boolean makeUser(String user, String password){
		char[] pw = password.toCharArray();
		
		return createUser(user, pw);
	}
	
	public boolean checkPass(String user, String password){
		char[] pw = password.toCharArray();
		
		return checkPassword(user, pw);
	}
	
	
	
	private boolean createUser(String user, char[] pw){
		boolean ok = false;
		Password password = new Password();
		password.user = user;
		password.password = generatePassword(pw);
		
		String fileName = user+"data.bin";
		
			
				try {
					ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(fileName));
					os.writeObject(password);
					os.close();
					ok = true;
					
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
//					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
//					e.printStackTrace();
				}
				
				return ok;
			
	}
	

	private boolean checkPassword(String user, char[] pw){
		boolean ok = false;
		String fileName = user+"data.bin";
		
		try {
			ObjectInputStream is = new ObjectInputStream(new FileInputStream(fileName));
			try {
				Password password = (Password) is.readObject();
				System.out.println(password.password);
				is.close();
				
				if(password.password == generatePassword(pw)){
					ok = true;
				}
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
//				e.printStackTrace();
			}
			
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
		}
		
		System.out.println(ok);
		
		
		return ok;
		
	}

	
	private int generatePassword(char[] password){
		int rc = -1;
		
		try{
		int ascii = 0;
		int i  = password.length;
		
		for(int e = 0; e < i; e++){
			System.out.println(password[e]);
			ascii = ascii*3+10 + (int) password[e];	
			System.out.println(ascii);
		}	
		rc = ascii;
		}
		catch(Exception e){
			System.out.println("virker ikke");
			
		}
		
		
		return rc;
	}


}
